//
//  MusicViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/7/31.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "MusicViewController.h"
#import "MusiciBottomCell.h"
#import "MusicManager.h"
#import "BigIntellgientModel.h"
#import "OpusListModel.h"

@interface MusicViewController ()<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic,strong)UIButton *playOrPauseBtn;
@property(nonatomic,strong)UISlider *slider;
@property(nonatomic,strong)UILabel *CurrentTimeLabel;
@property(nonatomic,strong)UILabel *totlaLabel;
@property(nonatomic,strong)UIImageView *headerImageView;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UICollectionViewFlowLayout *flowlayOut;
@property(nonatomic,strong)NSMutableArray *dataArray;
@end

@implementation MusicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [MusicManager shareInfo].index = 0;
    self.navigationItem.title = self.title;
    [self createBgViewAndButton];
    [self getDataModelWithFileid:self.fileId];
    // Do any additional setup after loading the view.
}
//创建播放页面的视图
-(void)createBgViewAndButton{
//    [self reloadDataWithIndex];
    UIImageView *bgImageView = [[UIImageView alloc] init];
    bgImageView.userInteractionEnabled = YES;
    [self.view addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        make.left.and.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.height.equalTo(self.view.mas_height).multipliedBy(0.6);
    }];
    // blur效果
    UIVisualEffectView *visualEfView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    visualEfView.frame = self.view.bounds;
    visualEfView.alpha = 1.0f;
    [bgImageView addSubview:visualEfView];
    _headerImageView = [[UIImageView alloc] init];
    [bgImageView addSubview:_headerImageView];
    [_headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgImageView.mas_centerX);
        make.top.equalTo(bgImageView.mas_top).offset(scaleTopAndBottom(125));
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(230), scaleLeftAndRight(230)));
    }];
    _headerImageView.layer.cornerRadius = scaleLeftAndRight(115);
    _headerImageView.layer.masksToBounds = YES;
    [_headerImageView sd_setImageWithURL:[NSURL URLWithString:self.picPath] placeholderImage:[UIImage imageNamed:@""]];
    UIView *bottomView = [[UIView alloc] init];
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = [UIColor whiteColor];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
        make.top.equalTo(bgImageView.mas_bottom);
    }];
    [bottomView layoutIfNeeded];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bottomView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(20, 20)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = bottomView.bounds;
    maskLayer.path = maskPath.CGPath;
    bottomView.layer.mask = maskLayer;
    
    _slider = [[UISlider alloc] init];
    [_slider addTarget:self action:@selector(progressAct:) forControlEvents:UIControlEventValueChanged];
    [bottomView addSubview:_slider];
    [_slider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bottomView.mas_centerX);
        make.top.equalTo(bottomView.mas_top).offset(scaleTopAndBottom(30));
        make.height.mas_equalTo(scaleTopAndBottom(3));
        make.left.equalTo(self.view.mas_left).offset(scaleLeftAndRight(40));
    }];
    _CurrentTimeLabel = [[UILabel alloc] init];
    _CurrentTimeLabel.textAlignment = NSTextAlignmentLeft;
    [bottomView addSubview:_CurrentTimeLabel];
    [_CurrentTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_slider.mas_bottom).offset(scaleTopAndBottom(20));
        make.left.equalTo(bottomView.mas_left).offset(scaleLeftAndRight(30));
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(100), scaleTopAndBottom(20)));
    }];
    _totlaLabel = [[UILabel alloc] init];
    _totlaLabel.textAlignment = NSTextAlignmentRight;
    [bottomView addSubview:_totlaLabel];
    [_totlaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_slider.mas_bottom).offset(scaleTopAndBottom(20));
        make.right.equalTo(bottomView.mas_right).offset(scaleLeftAndRight(-30));
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(100), scaleTopAndBottom(20)));
    }];
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [bottomView addSubview:leftBtn];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomView.mas_left).offset(scaleLeftAndRight(80));
        make.top.equalTo(_slider.mas_bottom).offset(scaleTopAndBottom(50));
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(40), scaleLeftAndRight(40)));
    }];
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [bottomView addSubview:rightBtn];
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bottomView.mas_right).offset(scaleLeftAndRight(-80));
        make.top.equalTo(_slider.mas_bottom).offset(scaleTopAndBottom(50));
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(40), scaleLeftAndRight(40)));
    }];
    _playOrPauseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [bottomView addSubview:_playOrPauseBtn];
    [_playOrPauseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bottomView.mas_centerX);
        make.top.equalTo(_slider.mas_bottom).offset(scaleTopAndBottom(50));
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(60), scaleLeftAndRight(60)));
    }];
    leftBtn.tag = 1000;
    rightBtn.tag = 1001;
    _playOrPauseBtn.tag = 1002;
    [leftBtn addTarget:self action:@selector(MusicRuntimeChoose:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn addTarget:self action:@selector(MusicRuntimeChoose:) forControlEvents:UIControlEventTouchUpInside];
    [_playOrPauseBtn addTarget:self action:@selector(MusicRuntimeChoose:) forControlEvents:UIControlEventTouchUpInside];
    self.flowlayOut = [[UICollectionViewFlowLayout alloc] init];
    self.flowlayOut.minimumLineSpacing = scaleLeftAndRight(5);
    self.flowlayOut.minimumInteritemSpacing = 0;
    self.flowlayOut.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.flowlayOut.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    self.flowlayOut.itemSize = CGSizeMake(scaleLeftAndRight(70), scaleTopAndBottom(90));
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowlayOut];
    self.collectionView.backgroundColor = [UIColor cyanColor];
    [bottomView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomView.mas_left).offset(scaleLeftAndRight(5));
        make.right.equalTo(bottomView.mas_right).offset(scaleLeftAndRight(-5));
        make.height.mas_equalTo(scaleTopAndBottom(110));
        make.bottom.equalTo(bottomView.mas_bottom).offset(scaleTopAndBottom(-10));
    }];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[MusiciBottomCell class] forCellWithReuseIdentifier:@"MusiciBottomCell"];
    [bgImageView sd_setImageWithURL:[NSURL URLWithString:self.picPath] placeholderImage:[UIImage imageNamed:@""]];
    _headerImageView.backgroundColor = [UIColor cyanColor];
    _slider.backgroundColor = [UIColor whiteColor];
    leftBtn.backgroundColor = [UIColor greenColor];
    rightBtn.backgroundColor = [UIColor greenColor];
    _playOrPauseBtn.backgroundColor = [UIColor orangeColor];
    _totlaLabel.backgroundColor = [UIColor clearColor];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAc) userInfo:nil repeats:YES];
}
- (void)timerAc{
    if ([MusicManager shareInfo].player.currentTime.timescale == 0 || [MusicManager shareInfo].player.currentItem.duration.timescale == 0) {
        
        return;
    }
    // 获得音乐总时长
    long long int totalTime = [MusicManager shareInfo].player.currentItem.duration.value / [MusicManager shareInfo].player.currentItem.duration.timescale;
    // 获得当前时间
    long long int currentTime = [MusicManager shareInfo].player.currentTime.value / [MusicManager shareInfo].player.currentTime.timescale;
    self.CurrentTimeLabel.text = [NSString stringWithFormat:@"%02lld:%02lld", currentTime / 60, currentTime % 60];
    self.totlaLabel.text = [NSString stringWithFormat:@"%02lld:%02lld", totalTime / 60, totalTime % 60];
    self.slider.maximumValue = totalTime;
    self.slider.minimumValue = 0;
    self.slider.value = currentTime;
    if (self.slider.value == totalTime) {
        [[MusicManager shareInfo] playNext];
        [self reloadDataWithIndex:[MusicManager shareInfo].index];
    }
    if ([MusicManager shareInfo].isPlay) {
        [UIView beginAnimations:@"rzoration" context:nil];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        self.headerImageView.transform = CGAffineTransformRotate(self.headerImageView.transform, 0.02);
        [UIView commitAnimations];
    }
}
-(void)MusicRuntimeChoose:(UIButton *)btn{
    if (btn.tag == 1000) {
        [_playOrPauseBtn setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
        [MusicManager shareInfo].musicArray = self.dataArray;
        [[MusicManager shareInfo] playPrevious];
        [self reloadDataWithIndex:[MusicManager shareInfo].index];
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:[MusicManager shareInfo].index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
    if (btn.tag == 1001) {
        [_playOrPauseBtn setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
        [[MusicManager shareInfo] playNext];
        [self reloadDataWithIndex:[MusicManager shareInfo].index];
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:[MusicManager shareInfo].index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        MusiciBottomCell *cell = (MusiciBottomCell *) [_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:[MusicManager shareInfo].index inSection:0]];
        cell.IfScale = YES;
        [UIView animateWithDuration:1 animations:^{
            cell.transform = CGAffineTransformMakeScale(1.3, 1.3);
        } completion:^(BOOL finished) {
            cell.transform = CGAffineTransformMakeScale(1.0, 1.0);
        }];
    }
    if (btn.tag == 1002) {
        if ([MusicManager shareInfo].isPlay == YES) {
            [btn setImage:[UIImage imageNamed:@"play"] forState:(UIControlStateNormal)];
        }else{
            [btn setImage:[UIImage imageNamed:@"pause"] forState:(UIControlStateNormal)];
        }
        [[MusicManager shareInfo] playAndPause];
    }
}
- (void)reloadDataWithIndex:(NSInteger)index
{
    // 寻找model
    OpusListModel *model = [MusicManager shareInfo].musicArray[index];
    // 改变图片 标题 音频
    self.navigationItem.title = model.name;
    // 修改播放歌曲
    [[MusicManager shareInfo] replaceItemWithUrlString:model.filepath];
}
-(void)progressAct:(id)sender{
        [[MusicManager shareInfo] playerProgressWithProgressFloat:((UISlider*)sender).value];
}
#pragma mark -collectionview的代理方法
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MusiciBottomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MusiciBottomCell" forIndexPath:indexPath];
    cell.model = self.dataArray[indexPath.row];
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    OpusListModel *model = self.dataArray[indexPath.row];
    self.navigationItem.title = model.name;
    NSString *videoUrl = model.filepath;
    NSString *musicStr = [NSString stringWithFormat:@"%@%@",PictureIp,videoUrl];
    // 修改播放歌曲
    [[MusicManager shareInfo] replaceItemWithUrlString:musicStr];
}
-(void)getDataModelWithFileid:(NSString *)fieldId{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *param = @{@"opusId":fieldId,@"type":self.type};
    NSString *url = ServerIp@"/opusApp/detailAll";
    [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        BigIntellgientModel *model = [BigIntellgientModel modelWithDictionary:jsonDict];
        self.navigationItem.title = model.fielName;
        NSString *videoUrl = model.videoPath;
        NSString *musicStr = [NSString stringWithFormat:@"%@%@",PictureIp,videoUrl];
        // 修改播放歌曲
        [[MusicManager shareInfo] replaceItemWithUrlString:musicStr];
        NSArray *dataArray = jsonDict[@"opusFileList"];
        for (NSDictionary *dic in dataArray) {
            OpusListModel *listModel = [OpusListModel modelWithDictionary:dic];
            [self.dataArray addObject:listModel];
        }
        [MusicManager shareInfo].musicArray = self.dataArray;
        [self.collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
@end
